<template>
  <div>
    <transition name="el-zoom-in-center">
      <div v-if="visible" class="cu-preview-main train-sign-time-config">
        <div class="cu-common-page-header">
          <el-page-header @back="visible = false" :content="'师训签到时间配置'" />
        </div>
        <div class="cu-common-layout">
          <div class="cu-common-layout-center">
            <el-row class="cu-common-search-box" :gutter="16">
              <el-form @submit.native.prevent>
                <el-col :span="6">
                  <el-form-item label="师训项目">
                    <el-select v-model="query.trainId" placeholder="请选择师训项目" clearable filterable>
                      <el-option v-for="item in trainOptions" :key="item.id" :label="item.title" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="配置日期">
                    <el-date-picker v-model="query.configDate" type="date" placeholder="选择配置日期" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="时段名称">
                    <el-input v-model="query.periodName" placeholder="请输入时段名称" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="search()">{{ $t('common.search') }}</el-button>
                    <el-button icon="el-icon-refresh-right" @click="reset()">{{ $t('common.reset') }}</el-button>
                  </el-form-item>
                </el-col>
              </el-form>
            </el-row>
            <div class="cu-common-layout-main cu-flex-main">
              <div class="cu-common-head">
                <div class="cu-common-head-left">
                  <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()">新增配置</el-button>
                  <el-button type="success" icon="el-icon-setting" @click="batchConfigHandle()">批量配置</el-button>
                </div>
                <div class="cu-common-head-right">
                  <el-tooltip content="刷新">
                    <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="reset()" />
                  </el-tooltip>
                </div>
              </div>
              <div class="cu-common-layout-main cu-flex-main">
                <custom-table v-loading="listLoading" :data="list" size="mini" @selection-change="selectionChangeHandle">
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column label="师训项目" width="200" show-overflow-tooltip>
                    <template slot-scope="scope">
                      {{ getTrainTitle(scope.row.trainId) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="configDate" label="签到日期" width="120" align="center" :formatter="custom.tableDateFormat" />
                  <el-table-column prop="periodName" label="时段" width="80" align="center">
                    <template slot-scope="scope">
                      <el-tag :type="getPeriodTagType(scope.row.periodName)" size="mini">
                        {{ getPeriodLabel(scope.row.periodName) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="startTime" label="开始时间" width="100" align="center" />
                  <el-table-column prop="endTime" label="结束时间" width="100" align="center" />
                  <el-table-column prop="lateMinutes" label="迟到阈值(分钟)" width="120" align="center" />
                  <el-table-column prop="isEnabled" label="状态" width="80" align="center">
                    <template slot-scope="scope">
                      <el-tag :type="scope.row.isEnabled ? 'success' : 'danger'" size="mini">
                        {{ scope.row.isEnabled ? '启用' : '禁用' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="remark" label="备注" show-overflow-tooltip />
                  <el-table-column prop="createTime" label="创建时间" width="150" align="center" :formatter="custom.tableDateTimeFormat" />
                  <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                      <el-button size="mini" type="text" @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
                      <el-button size="mini" type="text" class="cu-table-delBtn" @click="deleteHandle(scope.row.id)">删除</el-button>
                    </template>
                  </el-table-column>
                </custom-table>
                <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <!-- 新增/编辑弹窗 -->
    <Form v-if="formVisible" ref="Form" @refreshDataList="initData" />
    <!-- 批量配置弹窗 -->
    <BatchConfigForm v-if="batchConfigVisible" ref="BatchConfigForm" @refreshDataList="initData" />
  </div>
</template>

<script>
import { getTrainSignTimeConfigList, deleteTrainSignTimeConfig } from '@/api/campus/trainSignTimeConfig'
import { getTrainSelector } from '@/api/campus/train'
import Form from './Form'
import BatchConfigForm from './BatchConfigForm'

export default {
  name: 'TrainSignTimeConfig',
  components: {
    Form,
    BatchConfigForm
  },
  data() {
    return {
      visible: false,
      trainId: '',
      query: {
        trainId: '',
        configDate: '',
        periodName: ''
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      },
      total: 0,
      formVisible: false,
      batchConfigVisible: false,
      trainOptions: []
    }
  },
  created() {
    // 移除自动初始化，改为通过init方法调用
  },
  methods: {
    init(trainId) {
      this.trainId = trainId
      this.visible = true
      this.reset()
      // 设置默认的师训查询条件
      if (trainId) {
        this.query.trainId = trainId
      }
      this.initData()
      this.getTrainOptions()
    },
    search() {
      this.listQuery.currentPage = 1
      this.initData()
    },
    async initData() {
      this.listLoading = true
      try {
        const query = {
          ...this.listQuery,
          ...this.query
        }
        const res = await getTrainSignTimeConfigList(query)
        if (res.code === 200) {
          this.list = res.data || []
          this.total = (res.data.pagination && res.data.pagination.total) || 0
        }
      } catch (error) {
        console.error('获取数据失败:', error)
      } finally {
        this.listLoading = false
      }
    },
    async getTrainOptions() {
      try {
        const res = await getTrainSelector()
        if (res.code === 200) {
          this.trainOptions = res.data || []
        }
      } catch (error) {
        console.error('获取师训列表失败:', error)
      }
    },
    reset() {
      this.query = {
        trainId: '',
        configDate: '',
        periodName: ''
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      }
      this.initData()
    },
    selectionChangeHandle(val) {
      this.multipleSelection = val
    },
    addOrUpdateHandle(id) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.Form.init(id, this.trainId)
      })
    },
    batchConfigHandle() {
      this.batchConfigVisible = true
      this.$nextTick(() => {
        this.$refs.BatchConfigForm.init(this.trainId)
      })
    },
    deleteHandle(id) {
      this.$confirm('确定要删除该配置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await deleteTrainSignTimeConfig(id)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.initData()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },
    getPeriodTagType(period) {
      const typeMap = {
        AM: 'success',
        PM: 'warning',
        EVE: 'info'
      }
      return typeMap[period] || ''
    },
    getPeriodLabel(period) {
      const labelMap = {
        AM: '上午',
        PM: '下午',
        EVE: '晚上'
      }
      return labelMap[period] || period
    },
    getTrainTitle(trainId) {
      const train = this.trainOptions.find(item => item.id === trainId)
      return train ? train.title : '未知师训'
    }
  }
}
</script>

<style scoped>
.cu-common-layout {
  height: 100%;
}
.el-time-spinner__wrapper {
  width: 100% !important;
}
/* @import url(index.scss); */
</style>
